package com.sens.network;

import android.content.Context;

import com.sens.database.LiteOrmDBUtil;
import com.sens.tables.MybankOrder;
import com.yanzhenjie.nohttp.rest.Response;

public class MybankOrderCallback extends ResponseCallback<String> {
    private String orderId;
    private Context context;
    private int retryCount;
    private boolean needRetry = true;

    public MybankOrderCallback(Context context, String orderId) {
        this.context = context;
        this.orderId = orderId;
    }

    public MybankOrderCallback(Context context, String orderId, boolean needRetry) {
        this.context = context;
        this.orderId = orderId;
        this.needRetry = needRetry;
    }

    @Override
    public void onSucceed(int what, Response<String> response) {
        super.onSucceed(what, response);
        String result = response.get();
        if ("<Cad-rc-ok>".equals(result)) {
            MybankOrder mybankOrder = LiteOrmDBUtil.getGlobalDBUtil(context).queryOneByWhere(MybankOrder.class, "orderId", orderId);
            if (mybankOrder == null) return;
            mybankOrder.setHasUpload(true);
            LiteOrmDBUtil.getGlobalDBUtil(context).update(mybankOrder);
            onComplete(true, orderId, result);
            orderId = null;
            context = null;
        } else {
            onFailed(what, response);
        }
    }

    @Override
    public void onFailed(int what, Response<String> response) {
        super.onFailed(what, response);
        if (!needRetry || retryCount > 1) {
            String result = response.get();
            onComplete(false, orderId, result);
            orderId = null;
            context = null;
            return;
        }
        retryCount++;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    MybankOrder mybankOrder = LiteOrmDBUtil.getGlobalDBUtil(context).queryOneByWhere(MybankOrder.class, "orderId", orderId);
                    if (mybankOrder == null) return;
                    if (!mybankOrder.isHasUpload())
                        ApiByHttp.getInstance().uploadMybankOrder(mybankOrder, MybankOrderCallback.this);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    protected void onComplete(boolean isSuccess, String orderId, String msg) {
    }
}